<template>
    <div class="dict-container auto-height-container">
        <vab-query-form>
            <vab-query-form-left-panel :span="8">
                <el-button v-permissions="{
                    permission: ['system:dict:doAdd']
                }" type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
            </vab-query-form-left-panel>
            <vab-query-form-right-panel :span="16">
                <el-form :inline="true" :model="queryParams">
                    <el-form-item style="margin-right: 10px !important;">
                        <el-input v-model="queryParams.name" placeholder="请输入字典名称" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item style="margin-right: 10px !important;">
                        <el-input v-model="queryParams.code" placeholder="请输入字典编码" clearable
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item style="margin-right: 10px !important;">
                        <el-select v-model="queryParams.type" placeholder="请选择字典类型" clearable>
                            <el-option label="系统" value="system" />
                            <el-option label="内容" value="content" />
                        </el-select>
                    </el-form-item>
                    <el-form-item style="margin-right: 10px !important;">
                        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                            <el-option label="启用" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </vab-query-form-right-panel>
        </vab-query-form>

        <el-table v-loading="loading" :data="dictList" border height="100%" row-key="dict_id">
            <el-table-column type="expand">
                <template #default="{ row }">
                    <el-table :data="row.langs" border>
                        <el-table-column width="50">
                            <template #default="{ row: lang }">
                                <el-image :src="lang.language?.icon" style="width: 20px; height: 20px;"
                                    :preview-src-list="[]" />
                            </template>
                        </el-table-column>
                        <el-table-column label="语言" prop="language.name" width="120" />
                        <el-table-column label="名称" prop="name" min-width="120" />
                        <el-table-column label="备注" prop="remark" min-width="200" />
                        <el-table-column label="语言代码" prop="language.code" width="120" align="center" />
                        <el-table-column label="默认" width="80" align="center">
                            <template #default="{ row: lang }">
                                <el-tag v-if="lang.language?.is_default" type="success" size="small">是</el-tag>
                                <el-tag v-else type="info" size="small">否</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="name" label="字典名称" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="code" label="字典编码" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="type" label="字典类型" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="sort" label="排序" width="80" align="center" />
            <el-table-column label="状态" width="80" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                        {{ row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="create_time" label="创建时间" min-width="160" align="center" show-overflow-tooltip />
            <el-table-column prop="update_time" label="更新时间" min-width="160" align="center" show-overflow-tooltip />
            <el-table-column label="操作" width="280" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button type="primary" link @click="handleItems(row)" v-permissions="{
                        permission: ['system:dictItem:getList']
                    }">
                        字典项
                        <el-tag size="small" type="info" class="ml-1" round>{{ row.item_count || 0 }}</el-tag>
                    </el-button>
                    <el-button type="primary" link @click="handleEdit(row)" v-permissions="{
                        permission: ['system:dict:doEdit']
                    }">
                        编辑
                    </el-button>
                    <el-button type="danger" link @click="handleDelete(row)" v-permissions="{
                        permission: ['system:dict:doDelete']
                    }" :disabled="row.item_count > 0">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 字典表单组件 -->
        <dict-form v-model:visible="dialogVisible" :type="dialogType" :current-row="currentRow" @success="getList" />

        <!-- 字典项列表组件 -->
        <dict-items v-model:visible="itemsVisible" :dict-id="selectedDictId" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getDictList, deleteDict } from '/@/api/dict'
import type { Dict, DictQuery } from '/@/types/dict'
import DictForm from './components/DictForm.vue'
import DictItems from './components/DictItems.vue'

const loading = ref(false)
const total = ref(0)
const dictList = ref<Dict[]>([])
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentRow = ref<Dict | null>(null)
const itemsVisible = ref(false)
const selectedDictId = ref<number>(0)

// 查询参数
const queryParams = reactive<DictQuery>({})

// 获取列表数据
const getList = async () => {
    loading.value = true
    try {
        const { data } = await getDictList(queryParams)
        dictList.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

// 查询操作
const handleQuery = () => {
    queryParams.page = 1
    getList()
}

// 重置操作
const resetQuery = () => {
    queryParams.name = undefined
    queryParams.code = undefined
    queryParams.type = undefined
    queryParams.status = undefined
    handleQuery()
}

// 新增操作
const handleAdd = () => {
    dialogType.value = 'add'
    currentRow.value = null
    dialogVisible.value = true
}

// 编辑操作
const handleEdit = (row: Dict) => {
    dialogType.value = 'edit'
    currentRow.value = row
    dialogVisible.value = true
}

// 删除操作
const handleDelete = async (row: Dict) => {
    // 有子项时不允许删除
    if (row.item_count > 0) {
        ElMessage.warning('该字典下存在字典项，不能删除')
        return
    }

    try {
        await ElMessageBox.confirm(
            '确认要删除该字典吗？删除后将无法恢复！',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        await deleteDict(row.dict_id)
        ElMessage.success('删除成功')
        getList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
        }
    }
}

// 查看字典项
const handleItems = (row: Dict) => {
    selectedDictId.value = row.dict_id
    itemsVisible.value = true
}

onMounted(() => {
    getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-button.is-disabled) {
    opacity: 0.6;
    cursor: not-allowed;
}

:deep(.el-space) {
    justify-content: center;
}

.ml-1 {
    margin-left: 4px;
}

:deep(.el-button-group) {
    .el-button {
        display: inline-flex;
        align-items: center;

        .el-icon {
            margin-right: 4px;
        }
    }
}

:deep(.el-table__expanded-cell) {
    padding: 20px !important;
}

:deep(.el-table__expand-icon) {
    .el-icon {
        font-size: 12px;
    }
}

:deep(.el-image) {
    display: block;
    border-radius: 2px;
    overflow: hidden;
}
</style>